package com.tcm.smarthealth.controller;

import com.tcm.smarthealth.common.ApiResponse;
import com.tcm.smarthealth.common.exception.BusinessException;
import com.tcm.smarthealth.dto.HistoryResponse;
import com.tcm.smarthealth.enums.HistoryItemType;
import com.tcm.smarthealth.security.AuthContext;
import com.tcm.smarthealth.security.AuthenticatedUser;
import com.tcm.smarthealth.service.HistoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "健康档案", description = "问答与影像历史记录接口")
@RestController
@RequestMapping("/api/v1/history")
public class HistoryController {

    private final HistoryService historyService;

    public HistoryController(HistoryService historyService) {
        this.historyService = historyService;
    }

    @Operation(summary = "查询健康档案历史记录")
    @GetMapping
    public ApiResponse<HistoryResponse> listHistory(
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        AuthenticatedUser user = requireLogin();
        HistoryItemType itemType = parseType(type);
        HistoryResponse response = historyService.fetchHistory(user.getId(), itemType, page, size);
        return ApiResponse.success(response);
    }

    private AuthenticatedUser requireLogin() {
        AuthenticatedUser user = AuthContext.getCurrentUser();
        if (user == null) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED, "登录已失效，请重新登录");
        }
        return user;
    }

    private HistoryItemType parseType(String type) {
        if (type == null || type.isBlank()) {
            return null;
        }
        try {
            return HistoryItemType.valueOf(type.trim().toUpperCase());
        } catch (IllegalArgumentException ex) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "不支持的历史记录类型");
        }
    }
}

